package de.baumann.browser.activitys

import android.content.Context
import android.content.Intent
import android.net.http.SslError
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.webkit.*
import com.umeng.socialize.ShareAction
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import de.baumann.browser.R
import de.baumann.browser.db.Record
import de.baumann.browser.db.RecordAction
import de.baumann.browser.iview.IArticleDetailView
import de.baumann.browser.js.AppJs
import de.baumann.browser.present.ReadArticlePresenter
import de.baumann.browser.utils.*
import de.baumann.browser.views.dialog.CommentDialog
import de.baumann.browser.views.dialog.ComplaintDialog
import de.baumann.browser.views.dialog.LoadingDialog
import kotlinx.android.synthetic.main.activity_read_article.*
import kotlinx.android.synthetic.main.include_tool_bar.*

/**
 *@author:
 *@date:2019/7/14 19:15
 *@discription: 阅读文章
 */
class ReadArticleActivity : AbstractShareActivity<IArticleDetailView, ReadArticlePresenter>(), IArticleDetailView {

    private lateinit var action: RecordAction
    private lateinit var commentDialog: CommentDialog
    private lateinit var complaintDialog: CommentDialog
    private lateinit var appJs: AppJs
    private var likeType: Int = 1
    private var base64Img = ""
    private var shareType = 0
    private var cl = false
    var loadingDialog: LoadingDialog? = null

    companion object {
        fun startReadArticleActivity(context: Context, url: String, isComment: Boolean, description: String, id: String, commentNum: Int) {
            val intent = Intent(context, ReadArticleActivity::class.java).apply {
                putExtra("isComment", isComment)
                putExtra("title", context.getString(R.string.ODIN_headline))
                putExtra("description", description)
                putExtra("commentNum", commentNum)
                putExtra("isComplaint", true)
                putExtra("id", id)
                putExtra("url", url)
            }
            context.startActivity(intent)
        }

    }

    override fun getLayout(): Int {
        return R.layout.activity_read_article
    }

    override fun initView() {
//        readTitle.setPadding(0, ViewUtil.getStatusBarHeight(mContext), 0, 0)
        loadingDialog = LoadingDialog(this)
        loadingDialog?.show()
        readTitle.setPadding(0, 0, 0, 0)
        initToolbar(commToolBar, commTitle)
        WebView.setWebContentsDebuggingEnabled(true)
        appJs = AppJs(this)

        webArticle.addJavascriptInterface(appJs, "app")
        ViewUtil.configWebView(webArticle)
        val url = intent.getStringExtra("url")
        val params = "?l=${isLogined()}&xl=${getArticleId()}&xxl=${getUserId()}"

        webArticle.loadUrl(url + params)
        webArticle.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                if (newProgress == 100) {
                    Log.d("lwq", "onProgressChanged: " + newProgress)
                    loadingDialog?.dismiss()
                }
            }
        }
        webArticle.webViewClient = object : WebViewClient() {
            override fun onReceivedHttpError(view: WebView?, request: WebResourceRequest?, errorResponse: WebResourceResponse?) {
                super.onReceivedHttpError(view, request, errorResponse)
                loadingDialog?.dismiss()
            }

            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
//                view?.addJavascriptInterface(appJs, "app")
                view?.loadUrl(url)
                return true
            }
        }
        if (isCanComment()) {
            readBootomToolbar.visibility = View.VISIBLE
        }


        tvShareImage.setOnClickListener {
            cl = true
            webArticle.post {
                webArticle.loadUrl("javascript:getShareImage()")
            }
        }

        ivReadShare.setOnClickListener {
            displaySharePanel()
        }

        ivReaCollection.setOnClickListener {
            action.open(false)
            val record = Record(intent.getStringExtra("description"), intent.getStringExtra("url"), System.currentTimeMillis())
            action.addBookmark(record)
            action.close()
            ivReaCollection.setImageResource(R.drawable.ic_collectioned)
            ivReaCollection.isClickable = false
        }

        tvComment.setOnClickListener {
            commentDialog = CommentDialog(mContext, object : CommentDialog.OnCommentListenber {
                override fun comment(content: String) {
                    presenter.comment(content)
                }
            })
            commentDialog.show()
        }

        ivLike.setOnClickListener {
            presenter.like()
        }

        commentNum.setOnClickListener {
            webArticle.post {
                webArticle.loadUrl("javascript:displayCommentList()")
            }
        }
    }

    override fun createPresenter(): ReadArticlePresenter {
        return ReadArticlePresenter()
    }

    override fun createView(): IArticleDetailView {
        return this
    }

    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.shareToWechart -> {
                if (!ViewUtil.isInstalledWX(mContext)) {
                    showShortToast(getString(R.string.not_installed_WeChat))
                    return
                }
                if (shareType == 0) {
                    shareWeb(SHARE_MEDIA.WEIXIN)
                } else {
                    shareImage(SHARE_MEDIA.WEIXIN)
                }
            }
            R.id.shareToWXCircle -> {
                if (!ViewUtil.isInstalledWX(mContext)) {
                    showShortToast(getString(R.string.not_installed_WeChat))
                    return
                }
                if (shareType == 0) {
                    shareWeb(SHARE_MEDIA.WEIXIN_CIRCLE)
                } else {
                    shareImage(SHARE_MEDIA.WEIXIN_CIRCLE)
                }
            }
            R.id.shareToQQ -> {
                if (!ViewUtil.isInstalledQQ(mContext)) {
                    showShortToast(getString(R.string.not_installed_QQ))
                    return
                }
                if (shareType == 0) {
                    shareWeb(SHARE_MEDIA.QQ)
                } else {
                    shareImage(SHARE_MEDIA.QQ)
                }
            }
        }
    }

    override fun onRestart() {
        super.onRestart()
        if (cl) {
            presenter?.addwatchodin()
            cl = false
        }
    }

    private fun shareImage(platform: SHARE_MEDIA) {
        val umImage = UMImage(this, StringUtil.stringToBitmap(base64Img))
        umImage.setThumb(umImage)
        ShareAction(this)
                .setPlatform(platform)
                .withMedia(umImage)
                .share()
    }

    private fun shareWeb(platform: SHARE_MEDIA) {
        val umImage = UMImage(mContext, R.drawable.icon_share_thumb)
        val url = intent.getStringExtra("url")
        val params = "?xxxl=${getUser()?.inviteCode}&xxxxl=${MD5Util.md5encode(getArticleId() + "!@#$%^&*" + getUser()?.inviteCode, "UTF-8")}"
        val umweb = UMWeb(url + params)
        if (platform == SHARE_MEDIA.WEIXIN_CIRCLE) {
            umweb.title = intent.getStringExtra("description")
        } else {
            umweb.title = getString(R.string.ODIN_headline)
        }
        umweb.description = intent.getStringExtra("description")
        umweb.setThumb(umImage)
        val shareAction = ShareAction(this)
        shareAction.withMedia(umweb)
        shareAction.platform = platform
        shareAction.share()
    }

    override fun getTitleText(): String {
        return intent.getStringExtra("title")
    }

    private fun isCanComment(): Boolean {
        return intent.getBooleanExtra("isComment", false)
    }

    override fun initData() {
        if (isLogined() && isCanComment()) {
            presenter.queryLiked()
        }

        action = RecordAction(this)
        action.open(false)
        val isCollection = action.checkBookmark(intent.getStringExtra("url"))
        if (isCollection) {
            ivReaCollection.setImageResource(R.drawable.ic_collectioned)
            ivReaCollection.isClickable = false
        }
        action.close()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        if (isLogined() && intent.getBooleanExtra("isComplaint", false)) {
            menuInflater.inflate(R.menu.menu_complaint, menu)
        }
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        complaintDialog = ComplaintDialog(mContext, object : CommentDialog.OnCommentListenber {
            override fun comment(content: String) {
                presenter.complaint(content)
            }
        })
        complaintDialog.show()
        return super.onOptionsItemSelected(item)
    }

    override fun getArticleId(): String {
        if (intent.getStringExtra("id") == null) {
            return ""
        }
        return intent.getStringExtra("id")
    }

    private var countTimer2: CountTimer2? = null
    override fun setHasOdin(has: Boolean) {
        if (has) {
            tvShareImage.visibility = View.VISIBLE
            if (countTimer2 == null) {
                countTimer2 = CountTimer2(tvShareImage, "分享领红包", 10000)
            }
            countTimer2!!.start()
        } else {
            tvShareImage.visibility = View.GONE
        }
    }

    override fun setIsLike(isLike: Int) {
        if (isLike == 1) {
            this.likeType = 0
            ivLike.setImageResource(R.drawable.ic_liked)
        } else {
            this.likeType = 1
            ivLike.setImageResource(R.drawable.ic_like)
        }
        tvCommentNum.text = intent.getIntExtra("commentNum", 0).toString()
    }

    override fun getLikeType(): Int {
        return likeType
    }

    override fun commentSuccess() {
        showShortToast(getString(R.string.Comment_successful))
        commentDialog.dismiss()
    }

    override fun complaintSuccess() {
        showShortToast(getString(R.string.complaint_successful))
        complaintDialog.dismiss()
    }

    fun shareArticle() {
        shareType = 0
        if (isLogined()) {
            displaySharePanel()
        } else {
        }
    }

    fun shareArticleImg(baseImage: String) {
        shareType = 1
        this.base64Img = baseImage
        if (isLogined()) {
            displaySharePanel()
        } else {
        }
    }

}
